<!--
 * @Description: 项目管理
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 02/09/24 AM10:27
 -->
<!--setup-->
<script setup lang="jsx">
import { onMounted, getCurrentInstance, ref } from 'vue'
import BaseQueryFilter from '@shared/base/base-query-filter' // 搜索栏公共组件
import BaseQueryTable from '@shared/base/base-query-table' // 表格共公共组件
import SvgIcon from '@/components/svg-icon' // svg图标共公组件
import { openModal } from '@shared/base/open'
import prjInfoApi from '@/api/modules/prj-info' // api接口
import { to } from 'sf-utils2'
import useRouterPlus from '@/router/use-router-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProjectStart from './components/ProjectStart.vue' // 发起项目
import { $dict } from '@/utils/dict'

const { proxy } = getCurrentInstance()
const props = defineProps({})
const emit = defineEmits([])
const { router } = useRouterPlus()

/* 状态 */
const queryData = ref({})
const queryTable = ref({
  /**
   * @type {TToolsDescriptionsDataItem}
   */
  columns: [
    { label: '项目名称', prop: 'prjName', minWidth: 200, fixed: 'left' },
    { label: '项目编号', prop: 'prjCode', minWidth: 180 },
    { label: '核心业务编码', prop: 'coreCode', minWidth: 200 },
    { label: '创建时间', prop: 'createTime', minWidth: 180, isDate: true },
    { label: '项目类型', prop: 'prjType', minWidth: 90, dict: 'projectType' },
    { label: '出让方', prop: 'transferor', minWidth: 160 },
    { label: '资产总金额', prop: 'assetTotalAmt', minWidth: 160, isCurrency: true, align: 'right' },
    { label: '总户数', prop: 'debtorAmount', minWidth: 84, align: 'right' },
    { label: '总案件数', prop: 'caseAmount', minWidth: 84, align: 'right' },
    { label: '操作', slot: true, width: 146, fixed: 'right' }
  ],
  isHeaderSticky: true,
  onQuery: async (mark) => {
    const search = { ...queryData.value }
    if (search.createTimeRange && search.createTimeRange.length) {
      // 赋值创建开始、结束时间
      [search.createStartTime, search.createEndTime] = search.createTimeRange
      delete search.createTimeRange
    }

    const params = {
      pageNum: mark.pageNum,
      pageSize: mark.pageSize,
      ...search
    }
    const [res, err] = await to(prjInfoApi.getPrjInfoByPage(params))
    if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
    mark.total = res?.data?.total
    const list = res?.data?.dataList || []

    return {
      dataList: list,
      mark
    }
  }
})
const baseQueryTableRef = ref() // 表格实例

/* 方法 */
/**
 * 重置
 */
const onReset = () => {
  queryData.value = {}
  onSearch()
}

/**
 * 搜索
 */
const onSearch = () => {
  baseQueryTableRef.value.refresh({ pageNum: 1 })
}

/**
 * 发起项目
 */
const onStartProject = () => {
  openModal(
    ProjectStart,
    {},
    {
      title: '发起项目',
      minWidth: '480px',
      useDefaultButton: true,
      okButtonText: '提交',
      async onOk(modal, component, button) {
        try {
          button.setLoading(true)
          const res = await component.onSubmit()

          if (res) {
            onSearch()
            ElMessage.success('提交成功')
            await router.push({
              title: '编辑项目',
              path: '/project/approval/edit',
              query: {
                id: res.data // 项目id
              }
            })
            modal.close()
          }
        } catch (e) {
          console.log(e)
        } finally {
          button.setLoading(false)
        }
      },
      onClose(modal) {
        modal.close()
      }
    }
  )
}

/**
 * 编辑项目
 * @param row
 */
const onEdit = (row) => {
  router.push({
    title: '编辑项目',
    path: '/project/approval/edit',
    query: {
      id: row.id,
      coreCode: row.coreCode // 核心业务编码
    }
  })
}

/**
 * 查看项目
 * @param row
 */
const onView = (row) => {
  router.push({
    title: '查看项目',
    path: '/project/approval/detail',
    query: {
      id: row.id
    }
  })
}

/**
 * 删除项目
 * @param row
 */
const onDelete = (row) => {
  let label = <span style="color:#2D49D1">{row.prjName}</span>
  let title = <div>确定删除 {label}？项目数据删除后不可恢复，请谨慎操作。</div>
  ElMessageBox.confirm(title, '删除项目', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const params = {
      id: row.id, // 项目id
      updateTime: row.updateTime // 更新时间
    }
    const [res, err] = await to(prjInfoApi.removePrjInfoById(params))
    if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
    ElMessage.success(res?.message || '删除成功')
    baseQueryTableRef.value.refresh()
  })
}

/* 计算 */

/* 监听 */

/* 周期 */
onMounted(() => {})

/* 暴露 */
defineExpose({
  $: proxy.$
})
</script>

<!--render-->
<template>
  <div class="page">
    <!-- 内容区 -->
    <BaseQueryFilter.Main
      :is-show-collapsed-btn="false"
      :defaultCollapsed="false"
      @search="onSearch"
      @reset="onReset"
    >
      <BaseQueryFilter.Col label="项目名称">
        <el-input
          v-model="queryData.prjName"
          clearable
          placeholder="请输入"
        />
      </BaseQueryFilter.Col>
      <BaseQueryFilter.Col label="项目编号">
        <el-input
          v-model="queryData.prjCode"
          clearable
          placeholder="请输入"
        />
      </BaseQueryFilter.Col>
      <!--      <BaseQueryFilter.Col label="还款通道">
        <BaseQueryFilter.Select
          v-model="queryData.repayChnnl"
          :options="$dict('YesNo')"
          clearable
          placeholder="请选择"
        />
      </BaseQueryFilter.Col>-->
      <BaseQueryFilter.Col label="创建时间">
        <BaseQueryFilter.DatePicker
          v-model="queryData.createTimeRange"
          type="daterange"
          start-placeholder="请选择"
          end-placeholder="请选择"
        />
      </BaseQueryFilter.Col>
      <BaseQueryFilter.Col label="项目类型">
        <BaseQueryFilter.Select
          v-model="queryData.prjType"
          :options="$dict('projectType')"
          clearable
          placeholder="请选择"
        />
      </BaseQueryFilter.Col>
    </BaseQueryFilter.Main>

    <el-divider class="!mb-16px !mt-0" />

    <!-- 操作区域 -->
    <section class="page__operate">
      <div>项目列表</div>
      <el-button
        type="primary"
        @click="onStartProject"
      >
        <SvgIcon
          svg="approval/plus"
          size="14px"
          class="mr-2px"
        />发起项目
      </el-button>
    </section>

    <section class="page__content">
      <BaseQueryTable
        v-bind="queryTable"
        ref="baseQueryTableRef"
      >
        <template #操作="{ row }">
          <el-button
            type="text"
            @click="onView(row)"
          >
            查看
          </el-button>
          <el-button
            type="text"
            @click="onEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            @click="onDelete(row)"
          >
            删除
          </el-button>
        </template>
      </BaseQueryTable>
    </section>
  </div>
</template>

<!--style-->
<style scoped lang="less">
.page {
  min-height: var(--default-layout-page-view-min-height);
  padding: 16px;
  background: #fff;
  border-radius: 6px;

  .page__operate {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
  }

  .page__content {
    margin-top: 16px;
  }
}
</style>
